package com.roc.web.action.ysb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelExportService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbcarrtreward")
public class YsbCarryRewardQueryAction  extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(YsbCarryRewardQueryAction.class);
	private YsbCarryRewardQuerySearchCondition searchCondition;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	private IExcelExportService excelExportService;
	
	private InputStream excelFile;
	private String excelName;
	
	private String beginTime;
	
	private String agentFlag;

	@Action(value = "initCarryDetail", results = {
			@Result(name = "success", location = "/pages/ysb/ysbCarryRewardDetail.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String initCarryDetail() throws ServiceException{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		Map<String, String> mapReal;
		try {
			mapReal = powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
	        String superRole= mapReal.get("superRole");
	        if(!(superRole.equals(Role.AGENT.getCode())||superRole.equals(Role.SYSTEM.getCode())||superRole.equals(Role.O_MANAGER.getCode()))){
	        	addActionError("无访问权限");
	        	return ERROR;
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
     
		return SUCCESS;
	}
	
	@Action(value = "queryCarryDetail", results = { 
			@Result(name = "success", location = "/pages/ysb/ysbCarryRewardDetail.jsp"),
            @Result(name="error",location="/pages/ysb/ysbCarryRewardDetail.jsp"),
            @Result(name="login",location="/pages/ysb/ysbCarryRewardDetail.jsp") })

	public String queryProfitDetail() throws ServiceException{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(YsbCarryRewardQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new YsbCarryRewardQuerySearchCondition();
			}
		}
		try {
			//根据登录人角色显示不同代理商
			Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
	        String superRole= mapReal.get("superRole");
	        String opRealId =mapReal.get("opRealId");
	        if(!(superRole.equals(Role.AGENT.getCode())||superRole.equals(Role.SYSTEM.getCode())||superRole.equals(Role.O_MANAGER.getCode()))){
	        	addActionError("无访问权限");
	        	return ERROR;
	        }
	        searchCondition.setLoginid(Long.parseLong(opRealId));
			int rows=pagenitionService.countSQL(searchCondition);
			Calendar c = Calendar.getInstance();//默认是当前日期 
			long start =c.getTimeInMillis();
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			c = Calendar.getInstance();
			long end =c.getTimeInMillis();
			long  totalTime = end -start;
			c.setTimeInMillis(totalTime);
			logger.info("-- 云商宝携机入网返现导出查询需要语句:"+searchCondition.getSearchHQL()+"\n用时= "+ (c.get(Calendar.HOUR_OF_DAY)-8)+":"+ c.get(Calendar.MINUTE)+":"+ c.get(Calendar.SECOND)+":"+ c.get(Calendar.MILLISECOND));
			List<Object> tempList=new ArrayList<Object>();
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				while(iterator.hasNext()){
					Map<String,String> map=new HashMap<String,String>();
						Object[] obj=(Object[]) iterator.next();
						map.put("companyid", Constance.Null2EmptyTrim(obj[0]));
						map.put("agentname", Constance.Null2EmptyTrim(obj[1]));
						map.put("certifno", Constance.Null2EmptyTrim(obj[2]));
						map.put("mchtcd", Constance.Null2EmptyTrim(obj[3]));
						map.put("sn", Constance.Null2EmptyTrim(obj[4]));
						map.put("transamt", Constance.Null2EmptyTrim(obj[5]));
						map.put("stlmdate", Constance.Null2EmptyTrim(obj[6]));
						tempList.add(map);
				}
			}
			searchRsList=tempList;
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError("云商宝携机入网返现查询失败");
			
		}
		return SUCCESS;
	}
	
	
	@Action(value="exportCarryDetail",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=\"${excelName}\"",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/ysb/ysbCarryRewardDetail.jsp") }) 
	public String  exportProfitDetail() throws Exception{
		
				if(searchCondition==null){
					searchCondition=(YsbCarryRewardQuerySearchCondition)getSearchConditionFromSession();
					if(searchCondition==null){
						searchCondition=new YsbCarryRewardQuerySearchCondition();
					}
				}
				Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
		        String superRole= mapReal.get("superRole");
		        String opRealId =mapReal.get("opRealId");
		        if(!(superRole.equals(Role.AGENT.getCode())||superRole.equals(Role.SYSTEM.getCode())||superRole.equals(Role.O_MANAGER.getCode()))){
		        	addActionError("无访问权限");
		        	return ERROR;
		        }
		        searchCondition.setLoginid(Long.parseLong(opRealId));
				String temp = logingOperators.getRealName()+"--"+searchCondition.getBeginTime()+"云商宝携机入网返现明细.xls";	
	
				excelName=new String(temp.getBytes(),"ISO8859-1");
				try {
					Calendar c = Calendar.getInstance();//默认是当前日期 
					long start =c.getTimeInMillis();
					searchRsList=pagenitionService.findAllSQL(searchCondition, 0, 9999999);
					c = Calendar.getInstance();
					long end =c.getTimeInMillis();
					long  totalTime = end -start;
					c.setTimeInMillis(totalTime);
					logger.info("-- 云商宝携机入网返现导出查询需要语句:"+searchCondition.getSearchHQL()+"\n用时= "+ (c.get(Calendar.HOUR_OF_DAY)-8)+":"+ c.get(Calendar.MINUTE)+":"+ c.get(Calendar.SECOND)+":"+ c.get(Calendar.MILLISECOND));
					
					List<Object> tempList=new ArrayList<Object>();
					if(searchRsList!=null&&searchRsList.size()>0){
						Iterator iterator=searchRsList.iterator();
						while(iterator.hasNext()){ 
								Object[] obj=(Object[]) iterator.next();
								Object[] prof=new Object[7];
								prof[0]=Constance.Null2EmptyTrim(obj[0]);
								prof[1]=Constance.Null2EmptyTrim(obj[1]);
								prof[2]=Constance.Null2EmptyTrim(obj[2]);
								prof[3]=Constance.Null2EmptyTrim(obj[3]);
								prof[4]=Constance.Null2EmptyTrim(obj[4]);
								prof[5]=Constance.Null2EmptyTrim(obj[5]);
								prof[6]=Constance.Null2EmptyTrim(obj[6]);
								tempList.add(prof);
						}
					}
					searchRsList=tempList;
					String  reportName = "云商宝携机入网 返现列表";//标题名字
					String[]  headArray=new String[]{"所属大区","代理商名称","身份证号","商户号","终端号","交易额","统计月份"}; //表格列头
					
					HSSFWorkbook work=excelExportService.excelExport(reportName, headArray, searchRsList);

					 ByteArrayOutputStream output = new ByteArrayOutputStream();  
					         work.write(output);  
					   
					        byte[] ba = output.toByteArray();  
					         excelFile = new ByteArrayInputStream(ba);  
					         output.flush();  
					         output.close();  
					
		}catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_PROFIT_DASUM_QUERY);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_PROFIT_DASUM_QUERY, searchCondition);
	}


	public YsbCarryRewardQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(YsbCarryRewardQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public InputStream getExcelFile() {
		return excelFile;
	}


	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public String getBeginTime() {
		return beginTime;
	}

	public void setBeginTime(String beginTime) {
		this.beginTime = beginTime;
	}

	public String getAgentFlag() {
		return agentFlag;
	}

	public void setAgentFlag(String agentFlag) {
		this.agentFlag = agentFlag;
	}


}
